<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\LogService;
use Spatie\Activitylog\Models\Activity;

class LogAdminActivity
{
    protected $logService;

    public function __construct(LogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        // 只记录管理后台的操作
        if ($request->is('admin/*') && auth()->check()) {
            $this->logActivity($request, $response);
        }

        return $response;
    }

    /**
     * 记录活动日志
     */
    protected function logActivity(Request $request, $response)
    {
        $method = $request->method();
        $path = $request->path();
        $user = auth()->user();

        // 跳过日志管理相关的操作，避免循环记录
        if (str_contains($path, 'admin/logs')) {
            return;
        }

        // 跳过AJAX请求和API请求
        if ($request->ajax() || $request->expectsJson()) {
            return;
        }

        // 只记录POST、PUT、DELETE操作
        if (!in_array($method, ['POST', 'PUT', 'DELETE'])) {
            return;
        }

        // 获取操作描述
        $description = $this->getOperationDescription($method, $path, $request);

        // 获取操作对象
        $subject = $this->getOperationSubject($path, $request);

        // 获取操作属性
        $properties = $this->getOperationProperties($request);

        // 记录日志
        activity()
            ->causedBy($user)
            ->performedOn($subject)
            ->withProperties($properties)
            ->log($description);
    }

    /**
     * 获取操作描述
     */
    protected function getOperationDescription(string $method, string $path, Request $request): string
    {
        $segments = explode('/', $path);
        $module = $segments[1] ?? 'unknown';
        $action = $segments[2] ?? '';

        $moduleNames = [
            'users' => '用户',
            'rooms' => '房间',
            'dishes' => '菜品',
            'menus' => '菜单',
            'categories' => '分类',
            'orders' => '订单',
        ];

        $moduleName = $moduleNames[$module] ?? $module;

        switch ($method) {
            case 'POST':
                if (str_contains($action, 'create') || $action === '') {
                    return "创建了新的{$moduleName}";
                } elseif (str_contains($action, 'toggle')) {
                    return "切换了{$moduleName}状态";
                } elseif (str_contains($action, 'add')) {
                    return "添加了{$moduleName}项目";
                } else {
                    return "执行了{$moduleName}操作";
                }
            case 'PUT':
                return "更新了{$moduleName}信息";
            case 'DELETE':
                return "删除了{$moduleName}";
            default:
                return "执行了{$moduleName}操作";
        }
    }

    /**
     * 获取操作对象
     */
    protected function getOperationSubject(string $path, Request $request)
    {
        $segments = explode('/', $path);
        $module = $segments[1] ?? '';
        $id = $segments[2] ?? null;

        if (!$id || !is_numeric($id)) {
            return null;
        }

        $modelMap = [
            'users' => \App\Models\User::class,
            'rooms' => \App\Models\Room::class,
            'dishes' => \App\Models\Dish::class,
            'menus' => \App\Models\Menu::class,
            'categories' => \App\Models\Category::class,
            'orders' => \App\Models\Order::class,
        ];

        $modelClass = $modelMap[$module] ?? null;
        if (!$modelClass) {
            return null;
        }

        try {
            return $modelClass::find($id);
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * 获取操作属性
     */
    protected function getOperationProperties(Request $request): array
    {
        $properties = [
            'method' => $request->method(),
            'path' => $request->path(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ];

        // 添加请求数据（排除敏感信息）
        $data = $request->except(['password', 'password_confirmation', '_token']);
        if (!empty($data)) {
            $properties['data'] = $data;
        }

        return $properties;
    }
}
